package com.gdou.im.server.initializer;

import com.gdou.im.server.codeC.PacketToDataCodeC;
import com.gdou.im.server.codeC.WebSocketProtocolCodec;
import com.gdou.im.server.handler.LoginRequestHandler;
import com.gdou.im.server.handler.MessageRequestHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

/**
 * @ProjectName: demo
 * @Package: com.gdou.im.server.initializer
 * @ClassName: WebSocketChannelInitializer
 * @Author: carrymaniac
 * @Description:
 * @Date: 2020/6/16 4:52 下午
 * @Version:
 */
@Component
public class WebSocketChannelInitializer extends ChannelInitializer<NioSocketChannel> {
    private final WebSocketProtocolCodec webSocketProtocolCodec;
    private final MessageRequestHandler messageRequestHandler;
    private final LoginRequestHandler loginRequestHandler;
    private final PacketToDataCodeC packetToDataCodeC;

    public WebSocketChannelInitializer(WebSocketProtocolCodec webSocketProtocolCodec,MessageRequestHandler messageRequestHandler, LoginRequestHandler loginRequestHandler, PacketToDataCodeC packetToDataCodeC) {
        this.webSocketProtocolCodec = webSocketProtocolCodec;
        this.messageRequestHandler = messageRequestHandler;
        this.loginRequestHandler = loginRequestHandler;
        this.packetToDataCodeC = packetToDataCodeC;
    }

    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline().addLast(new HttpServerCodec());
        //大数据流处理
        ch.pipeline().addLast(new ChunkedWriteHandler());
        //HttpObjectAggregator：聚合器，聚合了FullHTTPRequest、FullHTTPResponse。。。，当你不想去管一些HttpMessage的时候，直接把这个handler丢到管道中，让Netty自行处理即可
        ch.pipeline().addLast(new HttpObjectAggregator(2048*64));
        //WebSocketServerProtocolHandler：给客户端指定访问的路由（/ws），是服务器端处理的协议，当前的处理器处理一些繁重的复杂的东西，运行在一个WebSocket服务端
        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
        //解码 TextWebSocketFrame => Packet
        ch.pipeline().addLast(webSocketProtocolCodec);
        ch.pipeline().addLast(packetToDataCodeC);
        //没有先后之分
        ch.pipeline().addLast(messageRequestHandler);
        ch.pipeline().addLast(loginRequestHandler);
    }
}
